<template>
  <div class="person-info-container">
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h3>个人信息</h3>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">
            编辑资料
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar">
              <div class="avatar-container">
                <el-avatar :size="80" :src="formatAvatarUrl(form.avatar)" class="user-avatar">
                  {{ form.username ? form.username.charAt(0).toUpperCase() : 'U' }}
                </el-avatar>
                <el-upload
                  v-if="isEditing"
                  class="avatar-uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange"
                >
                  <el-button type="primary" size="small">
                    <el-icon><EditPen /></el-icon> 更换头像
                  </el-button>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="保密" value="保密" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-input v-model="form.role" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="form.bio"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          />
        </el-form-item>

        <el-form-item label="修改密码" v-if="isEditing">
          <el-button type="primary" @click="showPasswordDialog">
            修改密码
          </el-button>
        </el-form-item>

        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存
          </el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handlePasswordChange"
            :loading="changingPassword"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import request from '@/utils/request'
import { EditPen } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const passwordFormRef = ref(null)
const isEditing = ref(false)
const submitting = ref(false)
const passwordDialogVisible = ref(false)
const changingPassword = ref(false)
const avatarFile = ref(null)
const API_BASE_URL = process.env.VUE_APP_BASE_API || '/api'

// 表单数据
const form = reactive({
  id: '',
  username: '',
  email: '',
  avatar: '',
  role: '',
  gender: '保密',
  phone: '',
  bio: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 格式化头像URL，确保包含API前缀
const formatAvatarUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整URL(包含http或https)，则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果已经包含API前缀，则直接返回
  if (url.startsWith(API_BASE_URL)) {
    return url
  }
  
  // 否则添加API前缀
  return `${API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度必须在3到50个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 100, message: '密码长度必须在6到100个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 处理头像更改
const handleAvatarChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return
  }
  
  avatarFile.value = file.raw
  uploadAvatar()
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', avatarFile.value)
    
    // 调用上传接口
    await request.post('/file/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      successMsg: '头像上传成功',
      onSuccess: (data) => {
        // 确保avatarUrl包含API前缀
        const avatarUrl = data
        
        // 更新表单中的头像
        form.avatar = avatarUrl.replace(API_BASE_URL, '')
      }
    })
  } catch (error) {
    console.error('头像上传失败:', error)
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
     await request.get(`/user/${userStore.userInfo.id}`,null,{
        showDefaultMsg:false,
        onSuccess:(data)=>{
          Object.assign(form, data)
        }
        
    })
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 处理编辑
const handleEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  fetchUserInfo() // 重新获取数据，放弃修改
}

// 处理提交
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await request.put(`/user/${userStore.userInfo.id}`, form,{
          showDefaultMsg:false,
          onSuccess:(data)=>{
            Object.assign(form, data)
              // 更新store中的用户信息
        userStore.setUserInfo({
          ...userStore.userInfo,
          username: form.username,
          email: form.email,
          avatar: form.avatar
        })
                ElMessage.success('保存成功')
        isEditing.value = false
          }
        })
    
        
      
      } catch (error) {
        console.error('保存用户信息失败:', error)
        ElMessage.error('保存用户信息失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 显示修改密码对话框
const showPasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 处理密码修改
const handlePasswordChange = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true
      try {
        await request.put(`/user/${form.id}/password`, null, {
          params: {
            oldPassword: passwordForm.oldPassword,
            newPassword: passwordForm.newPassword
          },
          successMsg: '密码修改成功',
          onSuccess: () => {
            // 关闭密码修改对话框
            passwordDialogVisible.value = false
            
            // 可以选择是否退出登录并重新登录
            userStore.logout()
            router.push('/login')
          }
        })
      } catch (error) {
        console.error('修改密码失败:', error)
      } finally {
        changingPassword.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.person-info-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .info-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 20px;
        color: var(--el-text-color-primary);
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 15px;

  .user-avatar {
    border: 2px solid #eaeaea;
    // background: linear-gradient(45deg, #6366F1, #EC4899);
  }

  .avatar-uploader {
    display: inline-block;
  }
}
</style> 